package cn.agiledata.bank.myspace.action;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import ocx.AESWithJCE;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import cn.agiledata.bank.account.dao.IAccountDAO;
import cn.agiledata.bank.account.service.AccountSummary;
import cn.agiledata.bank.account.service.IReturnCodeHolder;
import cn.agiledata.bank.audit.exception.AuditException;
import cn.agiledata.bank.audit.service.AuditRuleService;
import cn.agiledata.bank.common.bean.SelectBean;
import cn.agiledata.bank.common.exception.BusinessException;
import cn.agiledata.bank.common.servlet.InitForString;
import cn.agiledata.bank.common.util.Constant;
import cn.agiledata.bank.common.util.SecurityUtil;
import cn.agiledata.bank.common.util.StringUtil;
import cn.agiledata.bank.common.util.WeatherUtil;
import cn.agiledata.bank.hibernateBean.Account;
import cn.agiledata.bank.hibernateBean.OperSubacct;
import cn.agiledata.bank.hibernateBean.OperSubacctId;
import cn.agiledata.bank.hibernateBean.Operator;
import cn.agiledata.bank.myspace.exception.MySpaceException;
import cn.agiledata.bank.myspace.service.IMySpaceService;
import com.vnv.infrastructure.action.IPBBaseDynaForm;
import com.vnv.infrastructure.exception.IPBAppException;
import com.vnv.infrastructure.exception.IPBException;
import com.vnv.infrastructure.logic.IPBAppFactory;


public class OperatorManagerAction extends AbstractMySpaceAction {
	
	private AuditRuleService getAuditRuleService() {
		return (AuditRuleService) IPBAppFactory.getObj("auditRuleService");
	}
    protected IMySpaceService getMySpaceService() throws IPBException {
        return (IMySpaceService) IPBAppFactory.getObj(IMySpaceService.MGR_ID);
    }
	/**
	 * 操作员列表
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return ActionForward
	 * @throws BusinessException
	 */
	public ActionForward operator(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
	throws IPBException, Exception {
		AccountSummary user = (AccountSummary) WeatherUtil.getLoingInfoFromSession(request);
		if (user == null) {
			this.setReturnCode(request, IReturnCodeHolder.HASNOT_LOGON,OPERATOR_LIST);
			return mapping.findForward(FAILURE);
		}
		Account account = getMySpaceService().getAccount(String.valueOf(user.getAccountId()));
		//操作员List
		//List oprList = user.getOperatorList();
		IAccountDAO dao = (IAccountDAO) IPBAppFactory.getObj("accountDAO");
		request.setAttribute("oprList",dao.getOperatorsOfAccount(account));
		request.setAttribute("oprListSize", dao.getOperatorsOfAccount(account).size()+"");
		String accountType = account.getAccountType();
		request.setAttribute("accountType",accountType);
		return mapping.findForward(SUCCESS);
	}

	/**
	 * 跳转操作员权限设置列表*/
	public ActionForward toOperCompetenceList(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
	throws IPBException, Exception {
		AccountSummary user = (AccountSummary) WeatherUtil.getLoingInfoFromSession(request);
		if (user == null) {
			this.setReturnCode(request, IReturnCodeHolder.HASNOT_LOGON,OPERATOR_LIST);
			return mapping.findForward(FAILURE);
		}
		Account account = getMySpaceService().getAccount(String.valueOf(user.getAccountId()));
		//操作员List
		//List oprList = user.getOperatorList();
		IAccountDAO dao = (IAccountDAO) IPBAppFactory.getObj("accountDAO");
		request.setAttribute("oprList",dao.getOperatorsOfAccount(account));
		request.setAttribute("oprListSize", new Integer(dao.getOperatorsOfAccount(account).size()).toString());
		

		String accountType = account.getAccountType();
		request.setAttribute("accountType",accountType);
		return mapping.findForward(SUCCESS);
	}
	/**
	 * 跳转操作员权限设置**/
	public ActionForward toOperCompetenceModify(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
	throws IPBException, Exception {
		AccountSummary user = (AccountSummary) request.getSession(true).getAttribute(Constant.SESSION_ACCOUNT_SUMMARY);
		String seq = request.getParameter("seq");
		String actionTypeHere=request.getParameter("actionTypeHere");
		request.setAttribute("actionTypeHere", actionTypeHere);
		//根据操作者id得到操作者
		//Operator oper = user.getOperatorById(seq);
		Operator oper = user.getOperatorByIdInstance(seq);
		if(oper != null) {
			request.setAttribute("oper",oper);
			List list = user.getSubAccountList();
			request.setAttribute("subAccontList",list);
			List typeIdList = InitForString.getListId("OPER_TYPE");
			List typeNameList = InitForString.getListName("OPER_TYPE");
			List typeList = new ArrayList();
			if(typeIdList != null && typeNameList != null) {
				Object[] typeIdArray = (Object[])typeIdList.toArray();
				Object[] typeNameArray = (Object[])typeNameList.toArray();
				int size = typeIdArray.length;
				for(int i=0;i<size;i++) {
					SelectBean bean = new SelectBean(new Long((String)typeIdArray[i]),(String)typeNameArray[i]);
					typeList.add(bean);
				}
			}
			//edited by wubo 2008 3 28 start for 网关账户操作员权限修改列表区分普通企业账户
			if(COMPANY_TYPE_GATEWAY.equals(user.getAccount().getCompanyType())){
				SelectBean bean = new SelectBean(new Long(Constant.PERMIS_TYPE_RETURN),"退款");
				typeList.clear();
				typeList.add(bean);
			}
			//edited by wubo 2008 3 28 end
			request.setAttribute("typeList",typeList);
			
			Set operSubaccts = oper.getOperSubaccts();
			StringBuffer sb = new StringBuffer();
			if(operSubaccts != null) {
				Object[] objects = operSubaccts.toArray();
				int size = objects.length;
				for(int i=0;i<size;i++) {
					OperSubacct operSubacct = (OperSubacct)objects[i];
					OperSubacctId id = (OperSubacctId)operSubacct.getId();
					String subAccountId = id.getSubAccount().getId().toString();
					String listId = id.getSysbook().getId().getListId();
					if(i == 0) {
						sb.append(subAccountId).append(":").append(listId);
					} else {
						sb.append(",").append(subAccountId).append(":").append(listId);
					}
				}
			}
			request.setAttribute("selectStrings",sb.toString());
			return mapping.findForward(SUCCESS);			
		} else {
			this.setReturnCode(request,IReturnCodeHolder.GET_OPERATOR_ERROR,GET_OPERATOR);
			return mapping.findForward(FAILURE);
		}
	}
	/**
	 * 链接到新增操作员
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws IPBException
	 * @throws Exception
	 */
	public ActionForward toAddOperator(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
	throws IPBException, Exception {
		AccountSummary user = WeatherUtil.getLoingInfoFromSession(request);
		List list = user.getSubAccountList();
		request.setAttribute("subAccontList",list);
		List typeIdList = InitForString.getListId("OPER_TYPE");
		List typeNameList = InitForString.getListName("OPER_TYPE");
		List typeList = new ArrayList();
		if(typeIdList != null && typeNameList != null) {
			Object[] typeIdArray = (Object[])typeIdList.toArray();
			Object[] typeNameArray = (Object[])typeNameList.toArray();
			int size = typeIdArray.length;
			for(int i=0;i<size;i++) {
				SelectBean bean = new SelectBean(new Long((String)typeIdArray[i]),(String)typeNameArray[i]);
				typeList.add(bean);
			}
		}
		request.setAttribute("typeList",typeList);
		return mapping.findForward(SUCCESS);
	}
	
	/**
	 * 根据操作员id得到操作员
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws IPBException
	 * @throws Exception
	 */
	public ActionForward getOperator(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws IPBException, Exception {
		AccountSummary user = (AccountSummary) request.getSession(true).getAttribute(Constant.SESSION_ACCOUNT_SUMMARY);
		String seq = request.getParameter("seq");
		//根据操作者id得到操作者
		//Operator oper = user.getOperatorById(seq);
		Operator oper = user.getOperatorByIdInstance(seq);
		if(oper != null) {
			request.setAttribute("oper",oper);
			List list = user.getSubAccountList();
			request.setAttribute("subAccontList",list);
			List typeIdList = InitForString.getListId("OPER_TYPE");
			List typeNameList = InitForString.getListName("OPER_TYPE");
			List typeList = new ArrayList();
			if(typeIdList != null && typeNameList != null) {
				Object[] typeIdArray = (Object[])typeIdList.toArray();
				Object[] typeNameArray = (Object[])typeNameList.toArray();
				int size = typeIdArray.length;
				for(int i=0;i<size;i++) {
					SelectBean bean = new SelectBean(new Long((String)typeIdArray[i]),(String)typeNameArray[i]);
					typeList.add(bean);
				}
			}
			request.setAttribute("typeList",typeList);
			
			Set operSubaccts = oper.getOperSubaccts();
			StringBuffer sb = new StringBuffer();
			if(operSubaccts != null) {
				Object[] objects = operSubaccts.toArray();
				int size = objects.length;
				for(int i=0;i<size;i++) {
					OperSubacct operSubacct = (OperSubacct)objects[i];
					OperSubacctId id = (OperSubacctId)operSubacct.getId();
					String subAccountId = id.getSubAccount().getId().toString();
					String listId = id.getSysbook().getId().getListId();
					if(i == 0) {
						sb.append(subAccountId).append(":").append(listId);
					} else {
						sb.append(",").append(subAccountId).append(":").append(listId);
					}
				}
			}
			request.setAttribute("selectStrings",sb.toString());
			return mapping.findForward(SUCCESS);			
		} else {
			this.setReturnCode(request,IReturnCodeHolder.GET_OPERATOR_ERROR,GET_OPERATOR);
			return mapping.findForward(FAILURE);
		}
	}
	
	/**
	 * 添加操作员
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws IPBException
	 * @throws Exception
	 */
	public ActionForward addOperator(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws IPBException, Exception {
		IPBBaseDynaForm theForm = (IPBBaseDynaForm)form;
		String operatorCode = null;
		String operatorName = null;
		String mobile = null;
		String loginPass = null;
		String payPass = null;
		String operatorPosition = null;
		String operatorRemark = null;
		String[] operatorSubaccount = null;
		String auditFlag = null;
		operatorCode = theForm.getString("operatorCode").trim();
		operatorName = theForm.getString("operatorName") + "";
		mobile = theForm.getString("mobile") + "";
		operatorPosition = theForm.getString("operatorPosition") + "";
		operatorRemark = theForm.getString("operatorRemark") + "";
		
		HttpSession session = request.getSession();
		String mcrypt_key_1=(String)session.getAttribute("mcrypt_key");//获取session中随机因子
		session.removeAttribute("mcrypt_key");//清除session
		String password1 = theForm.getString("loginPass"); // 登录密码
		String password2=AESWithJCE.getResult(mcrypt_key_1,password1);
		
		String password3 = theForm.getString("payPass"); // 支付密码
		String password4=AESWithJCE.getResult(mcrypt_key_1,password3);
		
		loginPass = SecurityUtil.encryptoMD5String(password2); //登陆密码
		payPass = SecurityUtil.encryptoMD5String(password4); //支付密码
		
		operatorSubaccount = theForm.getStringArray("operatorSubaccount");		
		auditFlag = theForm.getString("auditFlag")+"";
		AccountSummary user = (AccountSummary) request.getSession(true)
				.getAttribute(Constant.SESSION_ACCOUNT_SUMMARY);
		if (user == null) {
			this.setReturnCode(request, IReturnCodeHolder.HASNOT_LOGON,ADD_OPERATOR);
			return mapping.findForward(FAILURE);			
		}

		try {
			Operator operator = user.addOrUpdateOperator(null, operatorCode,
					operatorName, mobile, loginPass, payPass, operatorPosition,operatorSubaccount,
					operatorRemark,auditFlag);
			request.setAttribute("operator",operator);
			return mapping.findForward(SUCCESS);
		} catch (BusinessException e) {
			log.error(e);
			this.setReturnCode(request, e.getReturnCode(),ADD_OPERATOR);
			return mapping.findForward(FAILURE);			
		}			

	}
	
	/**
	 * 修改操作员
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws IPBException
	 * @throws Exception
	 */
	public ActionForward modifyOperator(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws IPBException, Exception {
		IPBBaseDynaForm theForm = (IPBBaseDynaForm)form;
		String id;
		AccountSummary user = (AccountSummary) request.getSession(true)
		.getAttribute(Constant.SESSION_ACCOUNT_SUMMARY);
		if(!StringUtil.isStrEmpty(theForm.getString("oprId"))){
			 id = theForm.getString("oprId");
		}else{
			id = request.getParameter("seq").toString();
		}
		String operatorCode = null;
		String operatorName = null;
		String mobile = null;
		String loginPass = null;
		String payPass = null;
		String operatorPosition = null;
		String operatorRemark = null;
		String[] operatorSubaccount = null;
		String auditFlag = null;
		
		operatorCode = theForm.getString("operatorCode").trim();
		operatorName = theForm.getString("operatorName") + "";
		mobile = theForm.getString("mobile") + "";
		operatorPosition = theForm.getString("operatorPosition") + "";
		operatorRemark = theForm.getString("operatorRemark") + "";
		operatorSubaccount = theForm.getStringArray("operatorSubaccount");		
		auditFlag = theForm.getString("auditFlag")+"";
		if(Constant.NOT_VALID.equals(auditFlag)){
			if(getAuditRuleService().containsOperator(user.getAccountId(),new Long(id).longValue(),true)){
				throw MySpaceException.OPER_AMEND_FAILED;
			}
				
		}

		if (user == null) {
			this.setReturnCode(request, IReturnCodeHolder.HASNOT_LOGON,MODIFY_OPERATOR);
			return mapping.findForward(FAILURE);			
		}

		try {
			user.addOrUpdateOper(Long.valueOf(id), operatorCode,
					operatorName, mobile, loginPass, payPass, operatorPosition,
					operatorRemark,auditFlag);
		} catch (BusinessException e) {
			log.error(e);
			this.setReturnCode(request, e.getReturnCode(),MODIFY_OPERATOR);
			return mapping.findForward(FAILURE);			
		}

		return mapping.findForward(SUCCESS);			

	}
	/**
	 * 修改操作员的权限*/
	public ActionForward modifyOperatorConpetent(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws IPBException, Exception {
		IPBBaseDynaForm theForm = (IPBBaseDynaForm)form;
		String id;
		if(!StringUtil.isStrEmpty(theForm.getString("oprId"))){
			 id = theForm.getString("oprId");
		}else{
			id = request.getParameter("seq").toString();
		}
		String operatorCode = null;
		String operatorName = null;
		String mobile = null;
		String loginPass = null;
		String payPass = null;
		String operatorPosition = null;
		String operatorRemark = null;
		String[] operatorSubaccount = null;
		String auditFlag = null;
		
		operatorCode = theForm.getString("operatorCode").trim();
		operatorName = theForm.getString("operatorName") + "";
		mobile = theForm.getString("mobile") + "";
		operatorPosition = theForm.getString("operatorPosition") + "";
		operatorRemark = theForm.getString("operatorRemark") + "";
		operatorSubaccount = theForm.getStringArray("operatorSubaccount");		

		AccountSummary user = (AccountSummary) request.getSession(true)
				.getAttribute(Constant.SESSION_ACCOUNT_SUMMARY);
		if (user == null) {
			this.setReturnCode(request, IReturnCodeHolder.HASNOT_LOGON,MODIFY_OPERATOR);
			return mapping.findForward(FAILURE);			
		}

		try {
			user.addOrUpdateOperator(Long.valueOf(id), operatorCode,
					operatorName, mobile, loginPass, payPass, operatorPosition,operatorSubaccount,
					operatorRemark,auditFlag);
		} catch (BusinessException e) {
			log.error(e);
			this.setReturnCode(request, e.getReturnCode(),MODIFY_OPERATOR);
			return mapping.findForward(FAILURE);			
		}

		return mapping.findForward(SUCCESS);			

	}
	/**
	 * 删除操作员
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws IPBException
	 * @throws Exception
	 */
	public ActionForward deleteOperator(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws IPBException, Exception {

		String oprId = request.getParameter("key");
		Operator op = getMySpaceService().getOperatorById(oprId);
		if(Constant.INSIDE_STATUS_YES.equals(op.getAuditFlag()))
			throw MySpaceException.OPER_DEL_FAILED;
		if(getMySpaceService().ifOperUsed(oprId))
			throw MySpaceException.OPER_DELE_ERROR_FORUSED;
		AccountSummary user = (AccountSummary) request.getSession(true).getAttribute(Constant.SESSION_ACCOUNT_SUMMARY) ;
		if (user == null) {
			this.setReturnCode(request, IReturnCodeHolder.HASNOT_LOGON,DELETE_OPERATOR);
			return mapping.findForward(FAILURE);			
		}
		try {
			user.deleteOperator(oprId) ;
		} catch (BusinessException e) {
			log.error(e);
			this.setReturnCode(request, e.getReturnCode(),DELETE_OPERATOR);
			return mapping.findForward(FAILURE);			
		}
		return mapping.findForward(SUCCESS);
	}

	protected ActionForward getAppExceptionForward(ActionMapping mapping, ActionForm form, HttpServletRequest requst, HttpServletResponse response, IPBAppException arg4) {
		return mapping.findForward("delOperFailure");	
	}
	
	public ActionForward toInitAudit(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		return mapping.findForward(SUCCESS);
	}
	
	public ActionForward toInitAudit2(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		return mapping.findForward(SUCCESS);
	}



	

}
